package com.hlingsoft.xinsuo.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2015/3/4.
 */
public class Common {

    /**
     * 编码转化
     * @param str
     * @return
     */

    private static final double EARTH_RADIUS = 6378137;

    private static String date ;
    private static long orderNum = 0l;

    public static String encodeStr(String str) {
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * unicode转成Utf8
     * @param theString
     * @return
     */



    public static String unicodeToUtf8(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }




    /**
     * 字符串切割
     * @param str
     * @return
     */
    public static int getParts(String str){
        int count = 0;
        String[] sourceStrArray = str.split(",");
        for (int i = 0; i < sourceStrArray.length; i++) {
            count++;
        }
        return count;
    }

    public static List<String> strToList(String str){
        List<String>  stringList = new ArrayList<String>();
        String[] sourceStrArray = str.split(",");
        for (int i = 0; i < sourceStrArray.length; i++) {
            stringList.add(sourceStrArray[i]);
        }
        return stringList;
    }

    /**
     * 通过经纬度计算两地距离
     * @param lng_a
     * @param lat_a
     * @param lng_b
     * @param lat_b
     * @return
     */
    public static double getDistance(double lng_a, double lat_a, double lng_b,
                              double lat_b) {

        double radLat1 = (lat_a * Math.PI / 180.0);
        double radLat2 = (lat_b * Math.PI / 180.0);
        double a = radLat1 - radLat2;
        double b = (lng_a - lng_b) * Math.PI / 180.0;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s ;
    }






    /**
     * 判断操作系统是否是Windows
     */
    private static String OS = System.getProperty("os.name").toLowerCase();
    public static boolean isWindows(){
        return OS.indexOf("windows")>=0;
    }

    /**
     * 生成4位随机数
     * @return
     */
    public static String Randoms(){
        Random r = new Random();
        String code ="";
        for (int i = 0; i <4 ; i++) {
            int n5 = r.nextInt(10);
            code+=String.valueOf(n5);
        }
        return code;
    }

    /**
     * 判断是否是中文
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }




    /**
     * http Post请求
     * @return
     */
    public static String methodPost() {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(
                    "http://localhost:8080/vote/voting.json");
            System.out.println("请求: " + httppost.getRequestLine());
            httppost.setHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity entity1 = new StringEntity("[{\"id\":0,\"udId\":\"12\",\"name\":\"赵雷\",\"result\":1},{\"id\":0,\"udId\":\"12\",\"name\":\"张石\",\"result\":1},{\"id\":0,\"udId\":\"12\",\"name\":\"小雨\",\"result\":1}]", "application/json","UTF-8");
            httppost.setEntity(entity1);
            System.out.println(httppost.getEntity().getContent());

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: "
                        + entity.getContentLength());
            }
            // 显示结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    entity.getContent(), "UTF-8"));

            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            if (entity != null) {
                entity.consumeContent();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * long类型转化成date
     * @param lSysTime1
     * @return
     */
    public static Date transferLongToDate(long lSysTime1){
        SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date dt = new Date(lSysTime1 * 1000);
        return dt;
    }

    public static Date transferStringToDate(String sDt) throws ParseException {
        SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date dt2 = sdf.parse(sDt);
        return dt2;
    }







    public static synchronized String getDivId() {
        String str = new SimpleDateFormat("yyMMddHHmm").format(new Date());
        if(date==null||!date.equals(str)){
            date = str;
            orderNum  = 0l;
        }
        orderNum ++;
        long orderNo = Long.parseLong((date)) * 10000;
        orderNo += orderNum;;
        return orderNo+"";
    }


    /**
     * date类型时间差，秒数
     * @param d1
     * @param d2
     * @return
     */
    public static  long diffTime(Date d1,Date d2){
        long s = (d2.getTime()-d1.getTime()) /1000;
        return s;
    }






    /**
     * 分页
     * @param eventsList
     * @param off
     * @param row
     * @param <T>
     * @return
     */
    public static<T> List<T> fenYe(List<T> eventsList,int off,int row) {
        List<T> list = new ArrayList<T>();
        for (int i = 0; i <eventsList.size() ; i++) {
            if (i>=off&&i<off+row){
                list.add(eventsList.get(i));
            }
        }
        return list;
    }

}
